package cn.tnar.parkservice.controller.financia;


import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.model.dto.TParkOfflineCouponsDto;
import cn.tnar.parkservice.model.entity.TParkOfflineCoupons;
import cn.tnar.parkservice.service.ITParkOfflineCouponsService;
import cn.tnar.parkservice.service.KesbApiService;
import cn.tnar.parkservice.service.MqService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dzx
 * @ClassName:
 * @Description:
 * @date 2019年10月22日 09:08:00
 */
@Api(tags = "线下优惠券管理")
@RestController
@RequestMapping("service/coupon")
@Slf4j
public class CouponManagementController {


    @Autowired
    private KesbApiService kesbApiService;


    @Autowired
    private MqService mqService;

    @Autowired
    private ITParkOfflineCouponsService itParkOfflineCouponsService;

    private Gson gson = new Gson();


    /**
     * 创建线下优惠券
     *
     * @param param
     * @return ResultJson
     */
    @ApiOperation("创建线下优惠券")
    @PostMapping("/createOfflineCoupon")
    public ResultJson createOfflineCoupon(@RequestBody Map<String, Object> param) {
        try {
//            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.CREATE_OFFLINE_COUPON, param);
//            if (list != null && list.size() > 0) {
//                Map<String, String> stringStringMap = list.get(0);
//                String id = stringStringMap.get("id");
//                if (StringUtils.isNotBlank(id)) {
//                    TParkOfflineCoupons tParkOfflineCoupons = itParkOfflineCouponsService.getById(id);
//                    if (tParkOfflineCoupons != null) {
//                        String parkCode = tParkOfflineCoupons.getParkCode();
//                        TParkOfflineCouponsDto dto = new TParkOfflineCouponsDto()
//                                .setFree(tParkOfflineCoupons.getFree())
//                                .setTime_discont(tParkOfflineCoupons.getTimeDiscont())
//                                .setMoney_discont(tParkOfflineCoupons.getMoneyDiscont())
//                                .setState(tParkOfflineCoupons.getState())
//                                .setTime_userdefine(tParkOfflineCoupons.getTimeUserdefine())
//                                .setMoney_userdefine(tParkOfflineCoupons.getMoneyUserdefine())
//                                .setStart_time(tParkOfflineCoupons.getCreateTime())
//                                .setEnd_time(0L)
//                                .setCounpon_name(tParkOfflineCoupons.getParkName())
//                                .setId(tParkOfflineCoupons.getId())
//                                .setStatus(0);//新增
//                        mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.OFFLINE_COUPON_PREFIX + parkCode, JSON.toJSONString(dto));
//                        return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
//                    }
//                }
//            }
//            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
//
            log.info("创建线下优惠券:c接口请求参数,param======>" + param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.CREATE_OFFLINE_COUPON, param);
            log.info("创建线下优惠券:c接口返回参数,param======>" + gson.toJson(list));
            if (list != null && list.size() > 0) {
                Map<String, String> stringStringMap = list.get(0);
                String id = stringStringMap.get("id");
                if (StringUtils.isNotBlank(id)) {
                    String parkCode = (String) param.get("park_code");
                    pushAllOfflineCouponByParkCode(parkCode);
                    return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
                }
            }
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        } catch (Exception e) {
            log.error("创建线下优惠券===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }


    /**
     * 删除线下优惠券
     *
     * @param param
     * @return ResultJson
     */
    @ApiOperation("删除线下优惠券")
    @PostMapping("/deleteOfflineCoupon")
    public ResultJson deleteOfflineCoupon(@RequestBody Map<String, Object> param) {
        try {
//            String id = (String) param.get("id");
//            TParkOfflineCoupons tParkOfflineCoupons = itParkOfflineCouponsService.getById(id);
//            if (tParkOfflineCoupons != null) {
//                //下发删除优惠券的消息
//                String parkCode = tParkOfflineCoupons.getParkCode();
//                TParkOfflineCouponsDto dto = new TParkOfflineCouponsDto()
//                        .setFree(tParkOfflineCoupons.getFree())
//                        .setTime_discont(tParkOfflineCoupons.getTimeDiscont())
//                        .setMoney_discont(tParkOfflineCoupons.getMoneyDiscont())
//                        .setState(tParkOfflineCoupons.getState())
//                        .setTime_userdefine(tParkOfflineCoupons.getTimeUserdefine())
//                        .setMoney_userdefine(tParkOfflineCoupons.getMoneyUserdefine())
//                        .setStart_time(tParkOfflineCoupons.getCreateTime())
//                        .setEnd_time(0L)
//                        .setCounpon_name(tParkOfflineCoupons.getParkName())
//                        .setId(tParkOfflineCoupons.getId())
//                        .setStatus(2);//删除
//                mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.OFFLINE_COUPON_PREFIX + parkCode, JSON.toJSONString(dto));
//                List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.DELETE_OFFLINE_COUPON, param);
//            }
//            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(true);
            log.info("删除线下优惠券:c接口请求参数,param======>" + param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.DELETE_OFFLINE_COUPON, param);
            log.info("删除线下优惠券:c请求返回参数,param======>" + gson.toJson(list));
            String parkCode = (String) param.get("park_code");
            pushAllOfflineCouponByParkCode(parkCode);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(true);

        } catch (Exception e) {
            log.error("删除线下优惠券===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }


    /**
     * 更新线下优惠券
     *
     * @param param
     * @return ResultJson
     */
    @ApiOperation("更新线下优惠券")
    @PostMapping("/updateOfflineCoupon")
    public ResultJson updateOfflineCoupon(@RequestBody Map<String, Object> param) {
        try {
//            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.UPDATE_OFFLINE_COUPON, param);
//            String id = (String) param.get("id");
//            TParkOfflineCoupons tParkOfflineCoupons = itParkOfflineCouponsService.getById(id);
//            if (tParkOfflineCoupons != null) {
//                String parkCode = tParkOfflineCoupons.getParkCode();
//                TParkOfflineCouponsDto dto = new TParkOfflineCouponsDto()
//                        .setFree(tParkOfflineCoupons.getFree())
//                        .setTime_discont(tParkOfflineCoupons.getTimeDiscont())
//                        .setMoney_discont(tParkOfflineCoupons.getMoneyDiscont())
//                        .setState(tParkOfflineCoupons.getState())
//                        .setTime_userdefine(tParkOfflineCoupons.getTimeUserdefine())
//                        .setMoney_userdefine(tParkOfflineCoupons.getMoneyUserdefine())
//                        .setStart_time(tParkOfflineCoupons.getCreateTime())
//                        .setEnd_time(0L)
//                        .setCounpon_name(tParkOfflineCoupons.getParkName())
//                        .setId(tParkOfflineCoupons.getId())
//                        .setStatus(1);//修改
//                mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.OFFLINE_COUPON_PREFIX + parkCode, JSON.toJSONString(dto));
//            }
//            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
            log.info("更新线下优惠券:c接口请求参数,param======>" + param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.UPDATE_OFFLINE_COUPON, param);
            log.info("更新线下优惠券:c接口返回参数,param======>" + gson.toJson(list));
            String parkCode = (String) param.get("park_code");
            pushAllOfflineCouponByParkCode(parkCode);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("删除线下优惠券===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }


    /**
     * 使用统计量
     *
     * @param param
     * @return ResultJson
     */
    @ApiOperation("使用统计量")
    @PostMapping("/useStatistics")
    public ResultJson useStatistics(@RequestBody Map<String, Object> param) {
        try {
            log.info("使用统计量:c接口请求参数,param======>" + param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.USER_STATISTICS, param);
            log.info("使用统计量:c接口返回参数,param======>" + gson.toJson(list));
            //Collections.sort(list, Comparator.comparing(map->map.get("occur_date"),Comparator.reverseOrder()));
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("使用统计量===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }


    /**
     * 线下优惠券
     *
     * @param param
     * @return ResultJson
     */
    @ApiOperation("线下优惠券列表")
    @PostMapping("/offlineCouponList")
    public ResultJson offlineCouponList(@RequestBody Map<String, Object> param) {
        try {
            log.info("线下优惠券列表:c接口请求参数,param======>" + param);
            List<Map<String, String>> list = kesbApiService.queryKesbApiList(Constant.OFFLINE_COUPON_LIST, param);
            log.info("线下优惠券列表:c接口返回参数,param======>" + gson.toJson(list));
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        } catch (Exception e) {
            log.error("线下优惠券===>", e);
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(null);
        }
    }

    /**
     * 根据parkCode查询所有的优惠券并下发
     *
     * @param parkCode
     */
    private void pushAllOfflineCouponByParkCode(String parkCode) {
        if (StringUtils.isNotBlank(parkCode)) {
            QueryWrapper<TParkOfflineCoupons> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("park_code", parkCode);
            List<TParkOfflineCoupons> list = itParkOfflineCouponsService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                List<TParkOfflineCouponsDto> TParkOfflineCouponsDtoList = list.parallelStream().filter(x -> x != null)
                        .map(x -> new TParkOfflineCouponsDto().setFree(x.getFree())
                                .setTime_discont(x.getTimeDiscont())
                                .setMoney_discont(x.getMoneyDiscont())
                                .setState(x.getState())
                                .setTime_userdefine(x.getTimeUserdefine())
                                .setMoney_userdefine(x.getMoneyUserdefine())
                                .setStart_time(x.getCreateTime())
                                .setEnd_time(0L)
                                .setCounpon_name(x.getParkName())
                                .setId(x.getId()))
                        .collect(Collectors.toList());
                String str = JSON.toJSONString(TParkOfflineCouponsDtoList);
                mqService.convertAndSend(Constant.EXCHANGE_NAME, Constant.OFFLINE_COUPON_PREFIX + parkCode, str);
            }
        }
    }

}
